// import request from 'uni-request'
import { curEnv } from './env'
import { storageUtil } from './storage'

// 部分接口不需要token
const ignoreTokenApiList = ['/v1/common/setting']

const getBaseUrl = function(options = {}) {
  return curEnv.mainService
}

const getHeaders = function(url, options = {}) {
  let header = { Authorization: storageUtil.getToken() || '', 'Content-Type': 'application/json' }
  if (ignoreTokenApiList.includes(url.split('?')[0])) {
    header = {}
  }
  if (options.header) {
    header = { ...header, ...options.header }
  }
  return header
}

const filterRes = function(result = {}) {
  return new Promise((resolve, reject) => {
    let body = result.data
    if (result.statusCode !== 200 || !body) {
      return reject(new Error('processed'))
    }
    if (typeof body === 'string') {
      //  转换一下body类型，防止uni.uploadFile返回字符串不格式化
      try {
        body = JSON.parse(body)
      } catch (e) {}
    }
    if (String(body.code) === '10001') {
      storageUtil.setToken('')
      uni.reLaunch({
        url: '/pages/login/index?tip=1'
      })
      return reject(new Error('processed'))
    }
    if (body.errMessage) {
      uni.showToast({
        title: body.errMessage,
        icon: 'none'
      })
      return reject(new Error('processed'))
    } else {
      return resolve(body.data)
    }
  })
}

const request = function(url = '/', options = {}) {
  const httpUrl = getBaseUrl(options)
  const headers = getHeaders(url, options)
  return new Promise((resolve, reject) => {
    uni.request({
      url: httpUrl + url,
      method: options.method || 'GET',
      header: headers,
      data: options.data || {},
      success: (result) => {
        filterRes(result)
          .then((res) => {
            resolve(res)
          })
          .catch((e) => {
            reject(e)
          })
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

request.get = function(url = '/', data = {}, options = {}) {
  return request(url, { ...options, data })
}
request.post = function(url = '/', data = {}, options = {}) {
  return request(url, { ...options, data, method: 'POST' })
}
request.upload = function(url = '/', data = {}, fileUrl, options = {}) {
  const baseUrl = getBaseUrl(options)
  const headers = getHeaders(url, options)
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + url,
      header: headers,
      filePath: fileUrl,
      name: 'file',
      success: (result) => {
        filterRes(result)
          .then((res) => {
            resolve(res)
          })
          .catch((e) => {
            reject(e)
          })
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

export const http = request
